package com.tronsis.distribution.activity.me;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.tronsis.distribution.R;
import com.tronsis.distribution.bean.UploadFileBean;
import com.tronsis.distribution.bean.UserBean;
import com.tronsis.distribution.biz.factory.FileBizFactory;
import com.tronsis.distribution.biz.factory.UserBizFactory;
import com.tronsis.distribution.http.Url;
import com.tronsis.distribution.util.GlideImageLoader;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.db.DBUtil;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.imageloader.ImageLoader;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.LogUtil;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.util.WindowUtil;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WechatCardActivity extends ToolBarBaseActivity {

    @BindView(R.id.fly_wechat_card)
    FrameLayout mFlyWechatCard;
    @BindView(R.id.btn_save)
    Button mBtnSave;
    @BindView(R.id.iv_wechat_code)
    ImageView mIvWechatCode;
    @BindView(R.id.iv_icon_add)
    ImageView mIvIconAdd;
    private PopupWindow mPopupWindow;
    private static final int REQUEST_CAMERA = 125;
    private static final int REQUEST_ALBUM = 126;
    private String mWechatFid = "";
    final UserBean mUserBean = UserBizFactory.createBiz().getLoginUser(mContext);
    private String mType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wechat_card);
        ButterKnife.bind(this);
        setTitle(true, getString(R.string.upload_wechat_card));
        mType = getIntent().getType();
        if (StringUtil.isEquals(mType, "main")) {
            mWechatFid = getIntent().getStringExtra("wechatFid");
        } else {
            mWechatFid = mUserBean.getWechatVcardFid();
        }

        ImageLoader.display(mContext, Url.FILE_DOWNLOAD + mWechatFid, mIvWechatCode);

        if (mWechatFid == null) {
            mIvIconAdd.setVisibility(View.VISIBLE);
        } else {
            mIvIconAdd.setVisibility(View.GONE);
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS && data != null) {
            List<ImageItem> imageItems = (List<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            if (imageItems != null && imageItems.size() > 0) {
                mIvIconAdd.setVisibility(View.GONE);
                ImageLoader.display(mContext, imageItems.get(0).path, mIvWechatCode);
                httpUploadAvatar(new File(imageItems.get(0).path));
            }
        }
    }

    @OnClick(R.id.fly_wechat_card)
    void avatarClick() {
        showPopupWindow();
    }

    @OnClick(R.id.btn_save)
    void btnSaveClick() {
        if (StringUtil.isEquals(mType, "main")) {
            Intent intent = new Intent();
            intent.putExtra("wechatFid", mWechatFid);
            setResult(Activity.RESULT_OK, intent);
            finish();
        } else {
            httpUpdateUserInfo(mWechatFid);
        }
    }

    private void showPopupWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_album_camera, null);
        // 强制隐藏键盘
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        if (mPopupWindow == null) {

            ImagePicker imagePicker = ImagePicker.getInstance();
            imagePicker.setImageLoader(new GlideImageLoader());
            imagePicker.setCrop(true);
            imagePicker.setMultiMode(false);
            imagePicker.setShowCamera(true);
            imagePicker.setFocusHeight(DisplayUtil.getInstance(mContext).dip2px(240));
            imagePicker.setFocusWidth(DisplayUtil.getInstance(mContext).dip2px(240));

            mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setFocusable(true);
            mPopupWindow.setOutsideTouchable(true);
            /* mPopupWindow.setBackgroundDrawable(new BitmapDrawable());*/
            mPopupWindow.setAnimationStyle(R.style.AnimationBottomDialog);
            mPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    if (motionEvent.getAction() == MotionEvent.ACTION_OUTSIDE) {
                        mPopupWindow.dismiss();
                        return true;
                    }
                    return false;
                }
            });
            mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowUtil.setPopWindowBackgroundAlpha(WechatCardActivity.this, 1f);
                }
            });
            view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mPopupWindow.dismiss();
                }
            });
            view.findViewById(R.id.btn_camera).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mPopupWindow.dismiss();
                    checkPermission(new CheckPermListener() {
                        @Override
                        public void superPermission() {
                            Intent intent = new Intent(mContext, ImageGridActivity.class);
                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true);
                            startActivityForResult(intent, REQUEST_CAMERA);
                            mPopupWindow.dismiss();
                        }
                    }, R.string.ask_again, Manifest.permission.CAMERA);
                }
            });
            view.findViewById(R.id.btn_album).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mPopupWindow.dismiss();
                    checkPermission(new CheckPermListener() {
                        @Override
                        public void superPermission() {
                            Intent intent = new Intent(mContext, ImageGridActivity.class);
                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, false);

                            startActivityForResult(intent, REQUEST_ALBUM);
                            mPopupWindow.dismiss();
                        }
                    }, R.string.ask_again, Manifest.permission.READ_EXTERNAL_STORAGE);
                }
            });
        }
        WindowUtil.setPopWindowBackgroundAlpha(WechatCardActivity.this, 0.7f);
        mPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    private void httpUploadAvatar(final File file) {
        try {
            FileBizFactory.createBiz().upload(this, file, Url.FILE_TYPE_IMAGE, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    UploadFileBean fileBean = (UploadFileBean) data;
                    LogUtil.e("file", fileBean.getId());
                    mWechatFid = fileBean.getId();
                    dismissLoadingDialog();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void httpUpdateUserInfo(final String fileId) {
        try {

            UserBizFactory.createBiz().updateInfo(this, mUserBean.isAppNotice(), null, null, null, null, null, null, null, null, fileId, new UICallBack() {
                @Override
                public void onStart() {

                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    ImageLoader.display(mContext, Url.FILE_DOWNLOAD + fileId, mIvWechatCode);
                    mUserBean.setWechatVcardFid(fileId);
                    DBUtil.getInstance(mContext).update(mUserBean);
                    setResult(RESULT_OK);
                    finish();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }

    }
}
